#! /usr/bin/python 
# -*- coding: utf-8 -*-

import sqlite3
import sys
import os
import urllib2
import time
import getopt
from datetime import datetime

def Operate(dbFile,outputFile,projectName,projetVersion,startDate,endDate):
	wordList=["bug","issue","problem","fix","fixed","land","landed"]
	typicalWordList=["am","is","are","was","were","and","or","by","with","for","in","of","on","a","the","to","from","when","where","while","since","as","it","if"]
	
	startDate = datetime.strptime(startDate, '%Y-%m-%d')
	endDate = datetime.strptime(endDate, '%Y-%m-%d')
	
	conn = sqlite3.connect(dbFile)
	c = conn.cursor()
	c.execute("SELECT revisionNo,commitMessage FROM commitTable where projectName=? and projectVersion=? and commitDate between ? and ?", (projectName,projetVersion,str(startDate),str(endDate)))

	commitDict={}
	keyDict={}

	for row in c:
		commitDict[row[0]]=row[1]


	reportFileName = "%s" % (outputFile)
	report= open(reportFileName,'w')

	for commitNo,commitMessage in commitDict.iteritems():
		for word in wordList:
			if word in commitMessage:
				wordsInMessage=commitMessage.split(' ');
				for key in wordsInMessage:
					if key in keyDict:
						keyDict[key] +=1
					else: 
						keyDict[key]=1
				break

	for keyName,keyCount in keyDict.iteritems():
		if keyCount > 20 and keyName not in typicalWordList :
			report.write("%s\n" % (keyName))

def ShowHelp():
    print "Usage: generateKeys.py --dbfile [sqlite db file path] --projectname [name] --projectversion [version] --startdate [YYYY-MM-DD] --endDate [YYYY-MM-DD] --outputfile [output filepath for keywords (optional)]"    
    sys.exit(0)

if __name__ == "__main__":
	dbFile = None
	outputFile = None
	projectName=None
	projectVersion=None;
	startDate=None;
	endDate=None;
	try:
        	opts, args = getopt.getopt(sys.argv[1:],"f1:f2:f3:f4:f5:f6",["dbfile=","outputfile=","projectname=","projectversion=","startdate=","enddate="])
        	for opt, arg in opts:
			if opt in ("-f1", "--dbfile"):
				dbFile = arg
			elif opt in ("-f2", "--outputfile"):
				outputFile = arg
			elif opt in ("-f3", "--projectname"):
				projectName = arg
			elif opt in ("-f4", "--projectversion"):
				projectVersion = arg
			elif opt in ("-f5", "--startdate"):
				startDate = arg
			elif opt in ("-f6", "--enddate"):
				endDate = arg
		if len(sys.argv) == 1:
            		ShowHelp()
		elif not dbFile:
			print "DB File was not specified"
			ShowHelp()
		elif not projectName:
			print "Project name was not specified"
			ShowHelp()
		elif not projectVersion:
			print "Project version was not specified"
			ShowHelp()
		elif not startDate:
			print "Start date was not specified"
			ShowHelp()
		elif not endDate:
			print "End date was not specified"
			ShowHelp()
		elif not outputFile:
			outputFile="BugKeys"
			Operate(dbFile,outputFile,projectName,projectVersion,startDate,endDate)
		else:
			Operate(dbFile,outputFile,projectName,projectVersion,startDate,endDate)
	except getopt.GetoptError:
        	ShowHelp()


